package pkt

import (
	"strconv"
	"time"

	"github.com/google/gopacket/pcap"

	"gitee.com/konyshe/gogo"
)

type ProRePlay struct {
	handle *pcap.Handle
}

func NewProRePlay(deviceNum int) *ProRePlay {
	r := new(ProRePlay)
	r.Init(deviceNum)
	return r
}

func (c *ProRePlay) Release() {
	if c.handle == nil {
		c.handle.Close()
	}
}

func (c *ProRePlay) Init(deviceNum int) {
	if c.handle == nil {
		var err error

		devices, err := pcap.FindAllDevs()
		gogo.CheckError(err)

		// Open device
		c.handle, err = pcap.OpenLive(devices[deviceNum-1].Name, 1600, false, 30*time.Second)
		gogo.CheckError(err)

		gogo.LogInfo("Replay deviceNum: ", strconv.FormatInt(int64(deviceNum), 10))
	}
}

func (c *ProRePlay) Proc(data []byte) (err error) {
	return c.handle.WritePacketData(data)
}
